<template>
  <div class="dashboard">
    <a-page-header
      title="数据统计"
      sub-title="系统关键数据指标统计与可视化展示"
    />
    <a-divider />

    <div class="dashboard-content">
      <!-- 统计卡片区域 -->
      <a-row :gutter="[16, 16]">
        <a-col :xs="24" :sm="12" :lg="6">
          <a-card class="stat-card">
            <template #title>
              <div class="card-title">
                <team-outlined />
                <span>用户总数</span>
              </div>
            </template>
            <div class="stat-number">
              <count-to :start-val="0" :end-val="statistics.userCount" :duration="2000" />
            </div>
            <div class="stat-footer">
              <span>较上月</span>
              <span :class="statistics.userGrowth >= 0 ? 'growth-up' : 'growth-down'">
                {{ statistics.userGrowth >= 0 ? '+' : '' }}{{ statistics.userGrowth }}%
                <rise-outlined v-if="statistics.userGrowth >= 0" />
                <fall-outlined v-else />
              </span>
            </div>
          </a-card>
        </a-col>

        <a-col :xs="24" :sm="12" :lg="6">
          <a-card class="stat-card">
            <template #title>
              <div class="card-title">
                <file-image-outlined />
                <span>作品总数</span>
              </div>
            </template>
            <div class="stat-number">
              <count-to :start-val="0" :end-val="statistics.artworkCount" :duration="2000" />
            </div>
            <div class="stat-footer">
              <span>较上月</span>
              <span :class="statistics.artworkGrowth >= 0 ? 'growth-up' : 'growth-down'">
                {{ statistics.artworkGrowth >= 0 ? '+' : '' }}{{ statistics.artworkGrowth }}%
                <rise-outlined v-if="statistics.artworkGrowth >= 0" />
                <fall-outlined v-else />
              </span>
            </div>
          </a-card>
        </a-col>

        <a-col :xs="24" :sm="12" :lg="6">
          <a-card class="stat-card">
            <template #title>
              <div class="card-title">
                <thunderbolt-outlined />
                <span>活动总数</span>
              </div>
            </template>
            <div class="stat-number">
              <count-to :start-val="0" :end-val="statistics.activityCount" :duration="2000" />
            </div>
            <div class="stat-footer">
              <span>较上月</span>
              <span :class="statistics.activityGrowth >= 0 ? 'growth-up' : 'growth-down'">
                {{ statistics.activityGrowth >= 0 ? '+' : '' }}{{ statistics.activityGrowth }}%
                <rise-outlined v-if="statistics.activityGrowth >= 0" />
                <fall-outlined v-else />
              </span>
            </div>
          </a-card>
        </a-col>

        <a-col :xs="24" :sm="12" :lg="6">
          <a-card class="stat-card">
            <template #title>
              <div class="card-title">
                <comment-outlined />
                <span>评论总数</span>
              </div>
            </template>
            <div class="stat-number">
              <count-to :start-val="0" :end-val="statistics.commentCount" :duration="2000" />
            </div>
            <div class="stat-footer">
              <span>较上月</span>
              <span :class="statistics.commentGrowth >= 0 ? 'growth-up' : 'growth-down'">
                {{ statistics.commentGrowth >= 0 ? '+' : '' }}{{ statistics.commentGrowth }}%
                <rise-outlined v-if="statistics.commentGrowth >= 0" />
                <fall-outlined v-else />
              </span>
            </div>
          </a-card>
        </a-col>
      </a-row>

      <!-- 图表区域 -->
      <a-row :gutter="[16, 16]" style="margin-top: 16px">
        <a-col :span="24" :lg="12">
          <a-card title="近30天用户增长趋势">
            <div ref="userChartRef" style="height: 300px"></div>
          </a-card>
        </a-col>
        <a-col :span="24" :lg="12">
          <a-card title="作品分类分布">
            <div ref="categoryChartRef" style="height: 300px"></div>
          </a-card>
        </a-col>
      </a-row>

      <a-row :gutter="[16, 16]" style="margin-top: 16px">
        <a-col :span="24">
          <a-card title="近期活动数据统计">
            <a-table
              :columns="activityColumns"
              :data-source="activityData"
              :pagination="false"
              :loading="loading"
              bordered
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-tag :color="getStatusColor(record.status)">
                    {{ getStatusText(record.status) }}
                  </a-tag>
                </template>
                <template v-else-if="column.key === 'participantRate'">
                  <a-progress
                    :percent="record.participantRate"
                    size="small"
                    :status="record.participantRate > 60 ? 'success' : 'normal'"
                  />
                </template>
              </template>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue';
import { message, PageHeader } from 'ant-design-vue';
import { TeamOutlined, FileImageOutlined, ThunderboltOutlined, CommentOutlined, RiseOutlined, FallOutlined } from '@ant-design/icons-vue';
import { getDashboardStatistics, getUserGrowthTrend, getCategoryDistribution, getRecentActivities } from '@/api/statistics';
import * as echarts from 'echarts';

// 引入CountTo组件用于数字动画
const CountTo = {
  props: {
    startVal: {
      type: Number,
      default: 0
    },
    endVal: {
      type: Number,
      default: 0
    },
    duration: {
      type: Number,
      default: 1000
    },
    decimals: {
      type: Number,
      default: 0
    },
    autoplay: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      localStartVal: this.startVal,
      displayValue: this.formatValue(this.startVal),
      printVal: null,
      paused: false,
      localDuration: this.duration,
      startTime: null,
      timestamp: null,
      remaining: null,
      rAF: null
    };
  },
  computed: {
    countDown() {
      return this.startVal > this.endVal;
    }
  },
  watch: {
    startVal() {
      this.localStartVal = this.startVal;
      this.printVal = this.startVal;
      this.displayValue = this.formatValue(this.startVal);
    },
    endVal() {
      this.printVal = this.endVal;
      this.displayValue = this.formatValue(this.endVal);
    }
  },
  mounted() {
    if (this.autoplay) {
      this.start();
    }
    this.$emit('mountedCallback');
  },
  beforeUnmount() {
    this.clear();
  },
  methods: {
    start() {
      this.localStartVal = this.startVal;
      this.startTime = null;
      this.localDuration = this.duration;
      this.paused = false;
      this.rAF = requestAnimationFrame(this.count);
    },
    count(timestamp) {
      if (!this.startTime) this.startTime = timestamp;
      this.timestamp = timestamp;
      const progress = timestamp - this.startTime;
      this.remaining = this.localDuration - progress;

      if (this.countDown) {
        this.printVal = this.localStartVal - (this.localStartVal - this.endVal) * (progress / this.localDuration);
      } else {
        this.printVal = this.localStartVal + (this.endVal - this.localStartVal) * (progress / this.localDuration);
      }

      if (this.countDown) {
        this.printVal = this.printVal < this.endVal ? this.endVal : this.printVal;
      } else {
        this.printVal = this.printVal > this.endVal ? this.endVal : this.printVal;
      }

      this.displayValue = this.formatValue(this.printVal);

      if (progress < this.localDuration) {
        this.rAF = requestAnimationFrame(this.count);
      } else {
        this.$emit('callback');
      }
    },
    clear() {
      cancelAnimationFrame(this.rAF);
    },
    pause() {
      this.paused = true;
      this.clear();
    },
    resume() {
      this.paused = false;
      this.startTime = null;
      this.localDuration = this.remaining;
      this.rAF = requestAnimationFrame(this.count);
    },
    formatValue(val) {
      return Math.round(val).toLocaleString();
    }
  },
  render() {
    return this.displayValue;
  }
};

export default defineComponent({
  name: 'Dashboard',
  components: {
    TeamOutlined,
    FileImageOutlined,
    ThunderboltOutlined,
    CommentOutlined,
    RiseOutlined,
    FallOutlined,
    APageHeader: PageHeader,
    CountTo
  },
  setup() {
    const loading = ref(false);
    const userChartRef = ref(null);
    const categoryChartRef = ref(null);
    let userChart = null;
    let categoryChart = null;

    // 统计数据
    const statistics = reactive({
      userCount: 0,
      userGrowth: 0,
      artworkCount: 0,
      artworkGrowth: 0,
      activityCount: 0,
      activityGrowth: 0,
      commentCount: 0,
      commentGrowth: 0
    });

    // 活动表格列定义
    const activityColumns = [
      {
        title: '活动名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '开始时间',
        dataIndex: 'startTime',
        key: 'startTime',
      },
      {
        title: '结束时间',
        dataIndex: 'endTime',
        key: 'endTime',
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
      },
      {
        title: '作品数量',
        dataIndex: 'artworkCount',
        key: 'artworkCount',
      },
      {
        title: '参与率',
        dataIndex: 'participantRate',
        key: 'participantRate',
      }
    ];

    // 活动数据
    const activityData = ref([]);

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 0: return '投稿期';
        case 1: return '公示期';
        case 2: return '投票期';
        default: return '未知';
      }
    };

    // 获取状态颜色
    const getStatusColor = (status) => {
      switch (status) {
        case 0: return 'orange';
        case 1: return 'green';
        case 2: return 'red';
        default: return 'default';
      }
    };

    // 获取统计数据
    const getStatistics = async () => {
      loading.value = true;
      try {
        // 调用后端统计接口获取数据
        const response = await getDashboardStatistics();
        if (response.data.code === 200) {
          const data = response.data.data;
          statistics.userCount = data.userCount || 0;
          statistics.userGrowth = data.userGrowth || 0;
          statistics.artworkCount = data.artworkCount || 0;
          statistics.artworkGrowth = data.artworkGrowth || 0;
          statistics.activityCount = data.activityCount || 0;
          statistics.activityGrowth = data.activityGrowth || 0;
          statistics.commentCount = data.commentCount || 0;
          statistics.commentGrowth = data.commentGrowth || 0;
          
          // 获取活动列表数据用于表格展示
          fetchRecentActivities();
          
          // 初始化图表
          nextTick(() => {
            initUserChart();
            initCategoryChart();
          });
        } else {
          message.error(response.data.message || '获取统计数据失败');
        }
      } catch (error) {
        console.error('获取统计数据失败:', error);
        message.error('获取统计数据失败');
      } finally {
        loading.value = false;
      }
    };

    // 获取近期活动数据
    const fetchRecentActivities = async () => {
      try {
        const response = await getRecentActivities(5);
        if (response.data.code === 200) {
          activityData.value = response.data.data || [];
        } else {
          message.error(response.data.message || '获取活动数据失败');
          // 如果接口暂未实现，使用模拟数据
          activityData.value = [
            {
              id: 1,
              name: '2023年度摄影大赛',
              startTime: '2023-10-01 00:00:00',
              endTime: '2023-12-31 23:59:59',
              status: 2,
              artworkCount: 256,
              participantRate: 85
            },
            {
              id: 2,
              name: '春季创意设计展',
              startTime: '2023-11-15 00:00:00',
              endTime: '2024-01-15 23:59:59',
              status: 1,
              artworkCount: 128,
              participantRate: 62
            },
            {
              id: 3,
              name: '新年插画征集',
              startTime: '2023-12-01 00:00:00',
              endTime: '2024-02-01 23:59:59',
              status: 0,
              artworkCount: 76,
              participantRate: 45
            },
            {
              id: 4,
              name: '动漫角色设计大赛',
              startTime: '2023-12-15 00:00:00',
              endTime: '2024-03-15 23:59:59',
              status: 0,
              artworkCount: 42,
              participantRate: 28
            }
          ];
        }
      } catch (error) {
        console.error('获取活动数据失败:', error);
        message.error('获取活动数据失败');
      }
    };

    // 初始化用户增长趋势图表
    const initUserChart = async () => {
      if (!userChartRef.value) return;
      
      userChart = echarts.init(userChartRef.value);
      
      try {
        // 获取用户增长趋势数据
        const response = await getUserGrowthTrend();
        let dates = [];
        let userData = [];
        
        if (response.data.code === 200 && response.data.data) {
          const trendData = response.data.data;
          dates = trendData.dates || [];
          userData = trendData.counts || [];
        } else {
          // 如果接口暂未实现，使用模拟数据
          const now = new Date();
          for (let i = 29; i >= 0; i--) {
            const date = new Date(now);
            date.setDate(now.getDate() - i);
            dates.push(`${date.getMonth() + 1}/${date.getDate()}`);
            
            // 生成随机增长数据
            userData.push(Math.floor(Math.random() * 30) + 5);
          }
        }
      
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: dates,
            axisLabel: {
              interval: 5
            }
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '新增用户',
              type: 'line',
              smooth: true,
              data: userData,
              itemStyle: {
                color: '#1890ff'
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: 'rgba(24, 144, 255, 0.6)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(24, 144, 255, 0.1)'
                  }
                ])
              }
            }
          ]
        };
        
        userChart.setOption(option);
        
        // 响应窗口大小变化
        window.addEventListener('resize', () => {
          userChart && userChart.resize();
        });
      } catch (error) {
        console.error('初始化用户增长趋势图表失败:', error);
        message.error('初始化用户增长趋势图表失败');
      }
    };

    // 初始化作品分类分布图表
    const initCategoryChart = async () => {
      if (!categoryChartRef.value) return;
      
      categoryChart = echarts.init(categoryChartRef.value);
      
      try {
        // 获取分类分布数据
        const response = await getCategoryDistribution();
        let categoryData = [];
        let categoryNames = [];
        
        if (response.data.code === 200 && response.data.data) {
          categoryData = response.data.data;
          categoryNames = categoryData.map(item => item.name);
        } else {
          // 如果接口暂未实现，使用模拟数据
          categoryData = [
            { value: 1048, name: '摄影' },
            { value: 735, name: '插画' },
            { value: 580, name: '平面设计' },
            { value: 484, name: '3D设计' },
            { value: 300, name: 'UI设计' },
            { value: 200, name: '其他' }
          ];
          categoryNames = categoryData.map(item => item.name);
        }
        
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: categoryNames
          },
          series: [
            {
              name: '作品分类',
              type: 'pie',
              radius: ['50%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: categoryData
            }
          ]
        };
      
        categoryChart.setOption(option);
        
        // 响应窗口大小变化
        window.addEventListener('resize', () => {
          categoryChart && categoryChart.resize();
        });
      } catch (error) {
        console.error('初始化作品分类分布图表失败:', error);
        message.error('初始化作品分类分布图表失败');
      }
    };

    onMounted(() => {
      getStatistics();
    });

    return {
      loading,
      statistics,
      activityColumns,
      activityData,
      userChartRef,
      categoryChartRef,
      getStatusText,
      getStatusColor
    };
  }
});
</script>

<style scoped>
.dashboard {
  background-color: transparent;
}

.dashboard-content {
  margin-top: 20px;
}

.stat-card {
  height: 100%;
  transition: all 0.3s;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-5px);
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 16px;
}

.card-title .anticon {
  margin-right: 8px;
  font-size: 18px;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin: 16px 0;
  color: #1890ff;
}

.stat-footer {
  display: flex;
  justify-content: space-between;
  color: rgba(0, 0, 0, 0.45);
}

.growth-up {
  color: #52c41a;
}

.growth-down {
  color: #f5222d;
}
</style>